local gamelib = require "club.threecard.gamelib"
local pokerlib = require "club.threecard.pokerlib"
local coroutine = gamelib.coroutine

local poker_manager = {}

local poker_obj_temp = {};

local log = gamelib.logging.get("poker_manager");

local index = 1;

-- 后面如果有调试需求可以分到store里去
local map = {};

local function get_poker(poker_class)
    if not map[poker_class] then
        map[poker_class] = {};
    end

    if not map[poker_class].valid then
        map[poker_class].valid = {};
    end

    if not map[poker_class].invalid then
        map[poker_class].invalid = {}; 
    end

    local ret = nil;
    if #map[poker_class].valid > 0 then
        local index = #map[poker_class].valid;
        ret = map[poker_class].valid[index];

        table.remove(map[poker_class].valid);
    else
        ret = poker_class.new();
        ret.poker_class = poker_class;
    end

    index = index + 1;
    ret.poker_index = index;

    map[poker_class].invalid[index] = ret;

    if ret == nil then
        log.error("取Poker错误!");
    end

    return ret;
end

local function put_poker(poker)
    local poker_class = poker.poker_class;
    local poker_index = poker.poker_index;

    if not poker_class then
        return -1;
    end

    if not poker_index then
        return -2;
    end

    if not map[poker_class] then
        return -3;
    end

    if map[poker_class].invalid[poker_index] ~= poker then
        return -4;
    end

    map[poker_class].invalid[poker_index] = nil;
    table.insert(map[poker_class].valid, poker);
    poker:set_parent(pokerlib.core.root);
    poker:hide();

    return 1;
end

function poker_manager.get(data, poker_class)
    poker_class = poker_class or pokerlib.core.poker;
    local poker = get_poker(poker_class);
    poker:load(); --同步的
    poker:set_data(data);
    poker:on_get();
    poker:show();

    return poker;
end

function poker_manager.put(poker)
    local result = put_poker(poker);

    if result < 0 then
        log.error("回收Poker错误:"..result);
        return;
    end

    poker:on_put();
end

function poker_manager.clear()
    for _, poker_class in pairs(map) do
        if poker_class.invalid then
            for _, poker in pairs(poker_class.invalid) do
                poker_manager.put(poker);
            end
        end
    end
end

return poker_manager